<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <script src="js/echarts.min.js"></script>
    <script src="js/common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px; /* 新增页面边距 */
        }

        /* 新增主容器样式 */
        .chart-container {
            width: 90%;
            margin: 0 auto;
            /* padding: 20px;  */
            /* border: 1px solid #ddd; */
            /* box-shadow: 0 2px 4px rgba(0,0,0,0.1); */
        }

        /* 新增选项卡样式 */
        .tab-container {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-bottom: 10px;
        }
        .tab-button {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            background: #f8f9fa;
            font-size: 13px;
        }
        .tab-button.active {
            background: #2196F3;
            color: white;
            border-color: #2196F3;
        }
    </style>
</head>
<body>
<!-- 新增选项卡容器 -->
<div class="chart-container">
    <div class="tab-container" id="time-tabs"></div>
    <div id="ma-values" style="text-align: center; "></div>
    <!-- 新增展示容器，样式与ma-values保持完全一致 -->
    <div id="new-values" style="text-align: center; "></div>
    <div id="chart" style="width: 100%; height: 600px;"></div>
</div>

<script>
    let mockDataConfig = {};
    // 新增选项卡配置
    const TAB_CONFIG = [
        {name: '分时', type: 1},
        {name: '五日', type: 2},
        {name: '日K', type: 3},
        {name: '周K', type: 4},
        {name: '月K', type: 5},
        {name: '1分', type: 6},
        {name: '5分', type: 7},
        {name: '15分', type: 8},
        {name: '30分', type: 9},
        {name: '60分', type: 10},
        {name: '季K', type: 11},
        {name: '半年K', type: 13},
        {name: '年K', type: 12}
    ];

    // 新增全局变量存储当前类型
    let currentType = 1;  // 修改默认值为1(分时图)

    // 修改数据获取函数，区分分时图和K线图数据结构
    async function fetchKLineData(type) {
        try {
            // 新增URL参数获取逻辑
            const urlParams = new URLSearchParams(window.location.search);
            const searchCode = urlParams.get('searchCode') || 'sh000001';

            const response = await fetch(`http://localhost:8110/common/stock/V2/getKLine?type=${type}&searchCode=${searchCode}`);
            const result = await response.json();

            if (result.code === 200) {
                mockDataConfig.preClosePrice = result.data.preClosePrice;
                mockDataConfig.priceAndAvgPriceZdf = result.data.priceAndAvgPriceZdf;
                mockDataConfig.priceDecimal = result.data.priceDecimal;
                mockDataConfig.maxPrice = result.data.maxPrice;
                mockDataConfig.minprice = result.data.minprice;
                mockDataConfig.dateList = result.data.dateList;
                mockDataConfig.cfKLineType = result.data.cfKLineType;

                // 更新时间显示
                const timeLabel = document.getElementById('refresh-time');
                if (timeLabel) {
                    const now = new Date();
                    timeLabel.textContent = '刷新时间 ' + now.toLocaleTimeString('zh-CN', { hour12: false });
                }

                // 处理分时图数据结构
                if ([1, 2].includes(type)) {
                    return result.data.list.map(item => [  // 修改为访问 data.data.list
                        item.date,      // 日期
                        item.volume,    // 成交量
                        item.price,     // 价格
                        item.avgPrice,  // 均价
                        item.zdf,       // 涨跌幅
                        item.preClosePrice,        // 作日收盘价
                        item.priceAndAvgPriceZdf,  // 价格或平均价格的最大涨跌幅绝对值
                        item.priceDecimal,          // 价格精确小数位
                        item.volumeHuman
                    ]);
                }
                // 处理K线图数据结构
                return result.data.list.map(item => [  // 修改为访问 data.data.list
                    item.date,
                    item.open,
                    item.close,
                    item.low,
                    item.high,
                    item.volume,
                    item.zdf,
                    item.zf,
                    item.zde,
                    item.hsl,
                    item.volumeHuman,
                    item.diffVolumeHuman,
                    item.diffVolume
                ]);
            } else {
                console.error('接口请求失败:', result.msg);
                return [];
            }
        } catch (error) {
            console.error('数据获取失败:', error);
            return [];
        }
    }

    // 新增选项卡初始化
    function initTabs() {
        const tabContainer = document.getElementById('time-tabs');
        TAB_CONFIG.forEach(tab => {
            const button = document.createElement('div');
            button.className = `tab-button${tab.type === 1 ? ' active' : ''}`;  // 修改默认激活条件为类型1
            button.textContent = tab.name;
            button.onclick = () => {
                document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');

                // 清除已有定时器
                if (timerId) {
                    clearInterval(timerId);
                    timerId = null;
                }

                currentType = tab.type;
                renderChart();

                // 根据图表类型设置不同间隔（分时图2秒，其他45秒）
                const interval = [1].includes(currentType) ? getRefreshInterval(2000,45000) : 45000;
                timerId = setInterval(() => {
                    renderChart(true); // 定时更新禁用动画
                }, interval);
            };
            tabContainer.appendChild(button);
        });

        // 新增时间显示标签（在年K按钮右侧）
        const yearKButton = Array.from(tabContainer.children).find(btn => btn.textContent === '年K');
        if (yearKButton) {
            const timeLabel = document.createElement('span');
            timeLabel.id = 'refresh-time';
            timeLabel.style.padding = '6px 12px';
            timeLabel.style.color = '#666';
            yearKButton.after(timeLabel);
        }
    }

    let myChart = null;
    let touchStartX = 0;
    let isLongPress = false;
    let longPressTimer = null;
    // 新增全局变量声明
    let mockData = null;

    // 新增全局定时器变量声明
    let timerId = null;  // 解决timerId未定义问题

    // 新增全局防抖定时器
    let renderDebounce = null;

    // 修改后的页面可见性监听（移除停止定时器逻辑）
    document.addEventListener('visibilitychange', () => {
        // 删除原有停止定时器逻辑，仅保留页面不可见时暂停定时请求
        if (document.visibilityState === 'hidden') {
            stopTimer();
        } else {
            startTimer(); // 页面重新可见时重启定时器
        }
    });

    // 修改窗口聚焦/失焦事件监听（移除失焦停止逻辑）
    window.addEventListener('focus', startTimer);
    // 删除blur事件监听器：window.removeEventListener('blur', stopTimer);

    // 新增定时器控制函数（增加容错机制）
    function startTimer() {
        // 新增防止重复启动逻辑
        if (!timerId) {
            const interval = [1].includes(currentType) ? getRefreshInterval(2000,45000) : 45000;
            timerId = setInterval(() => {
                // 添加容错判断防止空指针
                if (myChart && !myChart.isDisposed()) {
                    renderChart(true);
                    if ([1, 2].includes(currentType)) {
                        updateNewValues({ dataIndexInside: mockData.length - 1 });
                    }
                }
            }, interval);
        }
    }

    function stopTimer() {
        if (timerId) {
            clearInterval(timerId);
            timerId = null;
        }
    }

    // 修改后的renderChart函数添加防抖
    async function renderChart(isScheduledUpdate = false) {
        // 新增防抖逻辑
        if (renderDebounce) {
            clearTimeout(renderDebounce);
        }
        renderDebounce = setTimeout(async () => {
            const chartDom = document.getElementById('chart');
            if (!chartDom) return;

            // 新增：根据类型控制元素显示逻辑
            const maValuesDiv = document.getElementById('ma-values');
            const newValuesDiv = document.getElementById('new-values');
            if ([1, 2].includes(currentType)) {
                // 处理分时图类型
                if (maValuesDiv) maValuesDiv.style.display = 'none';
                if (newValuesDiv) newValuesDiv.style.display = 'block';
            } else {
                // 处理K线图类型
                if (maValuesDiv) maValuesDiv.style.display = 'block';
                if (newValuesDiv) newValuesDiv.style.display = 'none';
            }

            // 新增：仅在类型变化时重新创建图表实例
            if (myChart && currentType !== currentRenderType) {
                myChart.dispose();
                myChart = null;
                chartDom.removeEventListener('touchstart', handleTouchStart);
                chartDom.removeEventListener('touchmove', handleTouchMove);
                chartDom.removeEventListener('touchend', handleTouchEnd);
            }

            if (!myChart) {
                myChart = echarts.init(chartDom);
                currentRenderType = currentType;
                chartDom.addEventListener('touchstart', handleTouchStart);
                chartDom.addEventListener('touchmove', handleTouchMove);
                chartDom.addEventListener('touchend', handleTouchEnd);
            }

            // 新增：根据类型控制均线值显示
            if ([1, 2].includes(currentType)) {
                maValuesDiv.style.display = 'none'; // 隐藏分时和五日均线显示
            } else {
                maValuesDiv.style.display = 'block'; // 显示其他类型均线
            }

            // 修改数据获取方式
            mockData = await fetchKLineData(currentType);
            if (mockData.length === 0) {
                // 修改：当数据为空时，设置一个空的option而不是返回
                myChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'center'
                    },
                    xAxis: {show: false},
                    yAxis: {show: false},
                    series: []
                }, {notMerge: true});
                return;
            }

            // 根据类型选择不同的配置（新增参数传递）
            const option = [1, 2].includes(currentType)
                ? createTimeChartOption(isScheduledUpdate)
                : createKLineChartOption();

            // 修改renderChart函数中的setOption调用方式
            myChart.setOption(option, { notMerge: true });  // 强制刷新图表

            // 在设置option后添加数据更新逻辑
            if ([1, 2].includes(currentType)) {
                updateNewValues({ dataIndexInside: mockData.length - 1 });
            } else {
                updateMAValues({ dataIndexInside: mockData.length - 1 });
            }

            // 在renderChart函数中修改事件监听逻辑
            myChart.on('updateAxisPointer', (event) => {
                updateMAValues(event);  // 统一处理所有系列悬浮事件
                updateNewValues(event);
            });
            myChart.on('globalout', () => {
                updateMAValues({ dataIndexInside: mockData.length - 1 });  // 鼠标移出时恢复最后一条
                updateNewValues({ dataIndexInside: mockData.length - 1 });
            });

            // 在设置完option后添加默认更新（修改为使用新参数）
            updateMAValues({ dataIndexInside: mockData.length - 1 });

        }, 200); // 200ms防抖间隔
    }

    // 新增触摸事件处理函数
    function handleTouchStart(e) {
        touchStartX = e.touches[0].clientX;
        longPressTimer = setTimeout(() => {
            isLongPress = true;
        }, 500);
    }

    function handleTouchMove(e) {
        if (!isLongPress) return;
        e.preventDefault();
        const touch = e.touches[0];
        const deltaX = touch.clientX - touchStartX;
        const totalData = mockData.length; // 修改为使用真实数据长度
        const percentPerData = 100 / totalData;

        // 根据滑动距离调整显示区间
        const currentOption = myChart.getOption();
        let newStart = currentOption.dataZoom[0].start - (deltaX * 0.5);
        let newEnd = currentOption.dataZoom[0].end - (deltaX * 0.5);

        // 边界控制
        newStart = Math.max(0, newStart);
        newEnd = Math.min(100, newEnd);
        if (newEnd - newStart < 60 * percentPerData) {
            newEnd = newStart + 60 * percentPerData;
        }

        myChart.dispatchAction({
            type: 'dataZoom',
            start: newStart,
            end: newEnd
        });

        touchStartX = touch.clientX;

        // 新增：滑动过程中实时更新均线值
        updateMAValues();
    }

    function handleTouchEnd() {
        clearTimeout(longPressTimer);
        isLongPress = false;
    }

    // 新增移动平均计算函数
    function calculateMA(dayCount) {
        const result = [];
        if (!mockData) return result; // 添加空值保护

        for (let i = 0; i < mockData.length; i++) {
            const startIndex = Math.max(0, i - dayCount + 1);
            const validData = mockData.slice(startIndex, i + 1);
            const sum = validData.reduce((acc, val) => acc + val[2], 0);
            result.push((sum / validData.length).toFixed(3));
        }
        return result;
    }

    // 修改ma值更新函数，添加类型判断
    function updateMAValues(event) {
        if ([1, 2].includes(currentType)) return;
        const maValuesDiv = document.getElementById('ma-values');
        let dataIndex = mockData.length - 1; // 默认最后一条

        // 增强数据索引获取逻辑：优先从轴信息获取，其次从事件参数获取
        if (event?.axesInfo?.[0]?.value !== undefined) {
            dataIndex = event.axesInfo[0].value;
        } else if (event?.dataIndexInside !== undefined) {
            dataIndex = event.dataIndexInside;
        }

        // 添加空值保护逻辑
        if (dataIndex < 0 || dataIndex >= mockData.length) {
            dataIndex = mockData.length - 1;
        }

        // 计算当前数据点对应的均线值
        const maValues = [5, 10, 20, 30, 60, 120, 360].map(dayCount => {
            const startIndex = Math.max(0, dataIndex - dayCount + 1);
            const validData = mockData.slice(startIndex, dataIndex + 1);
            const sum = validData.reduce((acc, val) => acc + val[2], 0);
            return validData.length > 0 ? (sum / validData.length).toFixed(mockDataConfig.priceDecimal) : '-';
        });

        maValuesDiv.innerHTML = `
            <span style="color: #FF9800;">MA5: ${maValues[0]}</span>,
            <span style="color: #2196F3;">MA10: ${maValues[1]}</span>,
            <span style="color: #4CAF50;">MA20: ${maValues[2]}</span>,
            <span style="color: #FF5722;">MA30: ${maValues[3]}</span>,
            <span style="color: #9C27B0;">MA60: ${maValues[4]}</span>,
            <span style="color: #3F51B5;">MA120: ${maValues[5]}</span>,
            <span style="color: #607D8B;">MA360: ${maValues[6]}</span>
        `;
    }

    // 修改DOMContentLoaded事件处理
    document.addEventListener('DOMContentLoaded', () => {
        initTabs();
        renderChart();
        startTimer(); // 使用新的定时器启动方式
    });

    // 新增页面卸载时清理定时器
    window.addEventListener('beforeunload', () => {
        if (timerId) {
            clearInterval(timerId);
        }
    });

    // 新增分时图配置函数（新增动画控制参数）
    function createTimeChartOption(isScheduledUpdate) {
        // 计算价格绝对值最大值
        const prices = mockData.map(item => item[2]);
        console.log(mockDataConfig)
        return {
            animation: currentType === 1 && !isScheduledUpdate,
            title: { show: false },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const item = mockData[params[0].dataIndex];
                    // 涨跌幅颜色判断逻辑
                    const zdf = item[4] || 0;
                    const color = zdf > 0 ? '#ec0000' : (zdf < 0 ? '#4caf50' : '#333');
                    
                    return `时间: ${item[0]}<br/>` + 
                        `价格:<span style="color: #2196F3;"> ${item[2]}</span><br/>` +  // 动态颜色
                        `均价:<span style="color: #FF9800;"> ${item[3].toFixed(mockDataConfig.priceDecimal)}</span><br/>` +  // 保持黄色
                        `涨幅:<span style="color: ${color}"> ${zdf.toFixed(2)}%</span><br/>` +  // 动态颜色
                        `成交量:<span style="color: #666;"> ${item[8] || item[1]?.toLocaleString() || '0'}</span>`;  // 优先显示volumeHuman
                }
            },
            axisPointer: {
                link: [
                    { xAxisIndex: [0, 1] }
                ],
                label: {
                    backgroundColor: '#d1d1d1'
                }
            },
            grid: [
                { left: '1%', right: '1%', height: '75%', top: '1%' },
                { left: '1%', right: '1%', top: '82%', height: '15%' }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: currentType === 1 ? mockDataConfig.dateList : mockData.map(item => item[0]), // 仅分时图使用dateList
                    gridIndex: 0,
                    axisLabel: {
                        show: true,
                        interval: function(index) {
                            // 每5分钟显示一个标签
                            return currentType === 1 ? index % 10 === 0 : index % 120 === 0;
                        }
                    },
                    axisPointer: {
                        show: true,
                        type: 'line',
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                {
                    type: 'category',
                    gridIndex: 1,
                    show: false,
                    data: currentType === 1 ? mockDataConfig.dateList : mockData.map(item => item[0]), // 仅分时图使用dateList
                    axisPointer: {
                        show: true,
                        triggerTooltip: true
                    }
                }
            ],
            yAxis: [
                { 
                    type: 'value', 
                    gridIndex: 0, 
                    min: mockDataConfig.minprice,
                    max: mockDataConfig.maxPrice,
                    interval: (mockDataConfig.maxPrice - mockDataConfig.minprice) / 4,
                    axisLabel: {
                        show: true,
                        position: 'left',
                        formatter: function(value) {
                            return value.toFixed(mockDataConfig.priceDecimal);
                        },
                        margin: -50,
                        padding: [0, 0, 0, 0],
                        align: 'right'
                    },
                    axisLine: {
                        show: true,
                        onZero: false
                    },
                    axisTick: {
                        show: true
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#f0f0f0',
                            type: 'dashed'
                        }
                    },
                    // 新增价格轴指针配置
                    axisPointer: {
                        show: true,
                        type: 'line',
                        label: {
                            show: true,
                            formatter: function(params) {
                                return params.value.toFixed(mockDataConfig.priceDecimal);
                            }
                        },
                        lineStyle: {
                            type: 'dashed',
                            width: 1
                        }
                    }
                },
                { 
                    type: 'value', 
                    gridIndex: 1, 
                    scale: true, 
                    axisLabel: { show: false },
                    // 新增量能轴指针配置
                    axisPointer: {
                        show: true,
                        type: 'line',
                        label: {
                            show: true,
                            formatter: function(params) {
                                return formatNumberToChineseUnit(params.value);
                            }
                        },
                        lineStyle: {
                            type: 'dashed',
                            width: 1
                        }
                    }
                }
            ],
            series: [
                { // 价格折线图
                    type: 'line',
                    data: mockData.map(item => item[2]),
                    symbol: 'none',
                    lineStyle: { color: '#2196F3', width: 1 },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                { // 均价折线图
                    type: 'line',
                    data: mockData.map(item => item[3]),
                    symbol: 'none',
                    lineStyle: { color: '#FF9800', width: 1, type: 'dashed' },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                { // 成交量柱状图
                    type: 'bar',
                    data: mockData.map(item => item[1] || null), // 处理无量能数据
                    itemStyle: {
                        color: function(params) {
                            const dataIndex = params.dataIndex;
                            if (dataIndex === 0) return '#26a69a'; // 首个数据点默认绿色
                            if (!mockData[dataIndex][1] || !mockData[dataIndex-1][1]) return '#666'; // 无量能数据
                            const current = mockData[dataIndex][1];
                            const prev = mockData[dataIndex - 1][1];
                            return current > prev ? '#ec0000' : '#26a69a';
                        }
                    },
                    xAxisIndex: 1,
                    yAxisIndex: 1
                }
            ]
        };
    }

    // 新增K线图配置函数
    function createKLineChartOption() {
        // 修改初始显示范围为最后150个数据点
        const totalData = mockData?.length || 0;
        const initialStart = totalData > 150
            ? Math.round((1 - 150 / totalData) * 100)
            : 0;

        return {
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const kData = params.find(p => p.seriesType === 'candlestick');
                    const vData = params.find(p => p.seriesType === 'bar');
                    let content = '';
                    
                    // 统一处理K线和量能的tooltip显示内容
                    const itemData = mockData[kData?.dataIndex || vData?.dataIndex];
                    if (!itemData) return '';
                    
                    const zdf = itemData[6] || 0;
                    const color = zdf > 0 ? '#ec0000' : (zdf < 0 ? '#4caf50' : '#333');
                    content += itemData[0] + '<br/>' +
                        '开盘: ' + (itemData[1]?.toFixed(mockDataConfig.priceDecimal) || '-') + '<br/>' +
                        '现价: <span style="color: #2196F3">' + (itemData[2]?.toFixed(mockDataConfig.priceDecimal) || '-') + '</span><br/>' +
                        '最低: ' + (itemData[3]?.toFixed(mockDataConfig.priceDecimal) || '-') + '<br/>' +
                        '最高: ' + (itemData[4]?.toFixed(mockDataConfig.priceDecimal) || '-') + '<br/>' +
                        `涨幅: <span style="color: ${color}">${(itemData[6]?.toFixed(2) || '-')}%</span><br/>` +
                        `振幅: ${(itemData[7]?.toFixed(2) || '-')}%<br/>` +
                        `涨跌额: <span style="color: ${color}">${(itemData[8]?.toFixed(mockDataConfig.priceDecimal) || '-')}</span><br/>` +
                        `换手率: ${(itemData[9]?.toFixed(2) || '-')}%<br/>` +
                        '成交量: ' + (itemData[10] || itemData[5]?.toLocaleString() || '-')  + '<br/>' +  // 优先显示volumeHuman
                        `成交差值: <span style="color: ${formatNumberColor(itemData[12])}">${(itemData[11] || '-')}</span>`
                    ;

                    return content;
                },
                axisPointer: { 
                    type: 'shadow',
                    link: { xAxisIndex: 'all' },
                    shadowStyle: {
                        color: 'rgba(150,150,150,0.15)',
                        width: 1
                    },
                    label: {
                        backgroundColor: '#d1d1d1'
                    }
                }
            },
            axisPointer: {  // 新增全局axisPointer配置
                link: [
                    { xAxisIndex: 'all' }  // 关联所有x轴
                ],
                label: {
                    backgroundColor: '#d1d1d1'  // 统一指针标签样式
                }
            },
            grid: [
                { left: '1%', right: '1%', height: '60%', top: '1%' },
                { left: '1%', right: '1%', top: '75%', height: '15%' }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: mockData.map(item => item[0]),
                    gridIndex: 0,
                    axisLabel: { rotate: 45 },
                    axisPointer: {
                        show: true,
                        type: 'shadow',
                        shadowStyle: {
                            color: 'rgba(150,150,150,0.15)',
                            width: 1
                        }
                    }
                },
                {
                    type: 'category',
                    gridIndex: 1,
                    show: false,
                    data: mockData.map(item => item[0]),
                    axisPointer: {  
                        show: true,
                        type: 'shadow',
                        shadowStyle: {
                            color: 'rgba(150,150,150,0.15)',
                            width: 1
                        }
                    }
                }
            ],
            yAxis: [
                { 
                    type: 'value', 
                    gridIndex: 0, 
                    scale: true,
                    splitArea: { show: true },
                    axisLabel: {
                        show: true,
                        position: 'left',
                        formatter: function(value) {
                            return value.toFixed(3);
                        },
                        margin: -50,
                        padding: [0, 0, 0, 50],
                        align: 'right'
                    },
                    axisLine: {
                        onZero: false
                    },
                    // 新增价格轴指针配置
                    axisPointer: {
                        show: true,
                        type: 'line',
                        label: {
                            show: true,
                            formatter: function(params) {
                                return params.value.toFixed(3);
                            }
                        },
                        lineStyle: {
                            type: 'dashed',
                            width: 1
                        }
                    }
                },
                { 
                    type: 'value', 
                    gridIndex: 1, 
                    scale: true, 
                    axisLabel: { show: false },
                    // 新增量能轴指针配置
                    axisPointer: {
                        show: true,
                        type: 'line',
                        label: {
                            show: true,
                            formatter: function(params) {
                                return formatNumberToChineseUnit(params.value);
                            }
                        },
                        lineStyle: {
                            type: 'dashed',
                            width: 1
                        }
                    }
                }
            ],
            series: [
                { // 保留原有K线系列配置
                    name: 'K线',
                    type: 'candlestick',
                    data: mockData.map(item => [item[1], item[2], item[3], item[4]]),
                    itemStyle: {
                        color: '#ec0000',
                        color0: '#26a69a',
                        borderColor: '#ec0000',
                        borderColor0: '#26a69a'
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                { // 保留原有成交量系列配置
                    name: '成交量',
                    type: 'bar',
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: mockData.map(item => item[5]),
                    itemStyle: {
                        color: function(params) {
                            const dataIndex = params.dataIndex;
                            if (dataIndex === 0) {
                                // 首个数据点无前值对比，默认显示绿色
                                return '#26a69a';
                            }
                            const currentVolume = mockData[dataIndex][5];
                            const prevVolume = mockData[dataIndex - 1][5];
                            return currentVolume > prevVolume ? '#ec0000' : '#26a69a';
                        }
                    }
                },
                // 新增均线系列
                {
                    name: 'MA5',
                    type: 'line',
                    data: calculateMA(5),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#FF9800',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA10',
                    type: 'line',
                    data: calculateMA(10),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#2196F3',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA20',
                    type: 'line',
                    data: calculateMA(20),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#4CAF50',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA30',
                    type: 'line',
                    data: calculateMA(30),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#FF5722',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA60',
                    type: 'line',
                    data: calculateMA(60),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#9C27B0',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA120',
                    type: 'line',
                    data: calculateMA(120),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#3F51B5',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    name: 'MA360',
                    type: 'line',
                    data: calculateMA(360),
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        color: '#607D8B',
                        width: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                }
            ],
            dataZoom: [{
                type: 'inside',
                xAxisIndex: [0, 1],
                start: initialStart,
                end: 100,
                filterMode: 'filter'
            }]
        };
    }

    // 新增new-values更新函数
    function updateNewValues(event) {
        if (![1, 2].includes(currentType)) return; // 非分时图不更新新值
        const newValuesDiv = document.getElementById('new-values');
        let dataIndex = mockData.length - 1; // 默认最后一条

        if (event?.dataIndexInside !== undefined) {
            dataIndex = event.dataIndexInside;
        }

        const item = mockData[dataIndex];
        if (!item) return;

        // 涨跌幅颜色判断逻辑
        const zdf = item[4] || 0;
        const color = zdf > 0 ? '#ec0000' : (zdf < 0 ? '#4caf50' : '#333');

        // 根据图表类型处理不同数据结构
        if ([1, 2].includes(currentType)) {
            newValuesDiv.innerHTML = `
                <span style="color: #2196F3;">价格: ${item[2]?.toFixed(mockDataConfig.priceDecimal) || '-'}</span>
                <span style="color: #FF9800; margin-left: 15px;">均价: ${item[3]?.toFixed(mockDataConfig.priceDecimal) || '-'}</span>
                <span style="color: ${color}; margin-left: 15px;">涨幅: ${item[4]?.toFixed(2) || '-'}%</span>
                <span style="color: #666; margin-left: 15px;">成交量: ${item[8]?.toLocaleString() || '-'}</span>
            `;
        } else {
            newValuesDiv.innerHTML = ``;
        }
    }

</script>

</body>
</html>
